package com.qw.flutter.xlog;

import android.content.Context;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

/**
 * @date: 2020/02/24
 * @author: lixu
 * @description: xlog日志插件
 */
public class LogPlugin implements FlutterPlugin, MethodChannel.MethodCallHandler {
    private static final String TAG = "LogPlugin";
    private static final String CHANNEL_NAME = "com.qw.flutter.xlog.plugins/xlog";
    private static final String INIT_METHOD = "init";
    private static final String APPENDER_FLUSH_METHOD = "appenderFlush";
    private static final String DESTROY_METHOD = "onDestroy";
    private static final String PRINT_METHOD = "log";

    private Context appContext;
    private MethodChannel channel;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        XXLog.i(TAG, "onAttachedToEngine");
        appContext = flutterPluginBinding.getApplicationContext();
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), CHANNEL_NAME);
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        XXLog.i(TAG, "onDetachedFromEngine");
        channel.setMethodCallHandler(null);
        XLogWrapper.getInstance().appenderFlush();
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        String methodName = call.method;
        if (PRINT_METHOD.equals(methodName)) {
            // xlog日志打印
            String level = call.argument("level");
            String tag = call.argument("tag");
            String msg = call.argument("msg");
            XLogWrapper.getInstance().printLog(level, tag, msg);
            result.success(null);
        } else if (INIT_METHOD.equals(methodName)) {
            // 初始化xlog
            XLogConfig xLogConfig = new XLogConfig();
            xLogConfig.logTag = (String) call.argument("logTag");
            xLogConfig.logPath = (String) call.argument("logPath");
            xLogConfig.isConsoleLogOpen = (Boolean) call.argument("isConsoleLogOpen");
            xLogConfig.encryptPubKey = (String) call.argument("encryptPubKey");

            XLogWrapper.getInstance().init(appContext, xLogConfig);
            result.success(null);
        } else if (APPENDER_FLUSH_METHOD.equals(methodName)) {
            XLogWrapper.getInstance().appenderFlush();
            result.success(null);
        } else if (DESTROY_METHOD.equals(methodName)) {
            XLogWrapper.getInstance().onDestroy();
            result.success(null);
        }
    }

}
